import os

from alipay import AliPay
from django.conf import settings
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from orders.models import OrderInfo
from .models import Payment


class PaymentView(APIView):
    """获取支付页面url"""
    permission_classes = [IsAuthenticated]

    def get(self, request, order_id):
        # 获取当前登录用户
        user = request.user
        try:
            # 判断订单数据是否正确  用户 订单号  支付方式  订单状态
            order = OrderInfo.objects.get(user=user, order_id=order_id, pay_method=OrderInfo.PAY_METHODS_ENUM['ALIPAY'],
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except Exception:
            return Response({'error_msg': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)

        # 向支付宝发送请求
        # 构造支付宝支付链接地址
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # 支付宝开发应用id
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 订单号
            total_amount=str(order.total_amount),  # 总金额
            subject="美多商城%s" % order_id,  # 支付项
            return_url="http://www.meiduo.site:8080/pay_success.html",  # 回调地址
        )

        # 拼接url返回给前端进行访问
        # 需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return Response({'alipay_url': alipay_url})


class PaymentStatusView(APIView):
    """用户支付成功后,会重定向回到商家支付成功的页面 并携带支付结果数据
    1.此时需要返回订单号  修改订单状态为待发货
    """

    def put(self, request):
        # 获取请求数据  query_dict
        data = request.query_params
        dict = data.dict()
        # 从参数字典中获取signature用以校验
        signature = dict.pop('sign')

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        success = alipay.verify(dict, signature)
        if success:
            # 创建订单流水号记录
            # 订单编号 支付宝返回的参数名称都是固定的
            order_id = data.get('out_trade_no')
            # 支付宝支付流水号
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )
            # 修改订单表中的订单状态
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            return Response({'trade_id': trade_id})
        else:
            return Response({'message': '非法请求'}, status=status.HTTP_403_FORBIDDEN)
